<template>
	<!-- 二次封装-全选多选框组件 -->
	<section class="my-checkbox">
		<el-checkbox
			style="display: inline-block; width: 70px;"
			:border="border"
			:indeterminate="isIndeterminate"
			v-model="checkAll"
			@change="allChange"
			>全选</el-checkbox
		>

		<el-checkbox-group
			style="display: inline-block; height: 28px;"
			v-model="source"
			@change="radioChange"
		>
			<el-checkbox
				:border="border"
				v-for="(s, i) in boxs"
				:label="s.value"
				:key="i"
				>{{ s.name }}</el-checkbox
			>
		</el-checkbox-group>
	</section>
</template>

<script>
export default {
	// 选择项  选择框
	props: {
		value: {
			type: Array,
			required: true,
			default: function () {
				return []
			},
		},
		boxs: {
			type: Array,
			required: true,
			default: function () {
				return [
					{
						name: '',
						value: '',
					},
				]
			},
		},
		border: {
			type: Boolean,
			required: false,
			default: false,
		},
		span: {
			type: Number,
			required: false,
			default: 21,
		},
	},
	watch: {
		source(newValue, oldValue) {
			this.$emit('input', newValue)
		},
		// 动态赋值

		value(newVale, oldVal) {
			this.source = newVale
		},
	},
	mounted() {
		this.isIndeterminate = this.source.length < this.boxs.length
		this.checkAll = !this.isIndeterminate
	},
	data() {
		return {
			// 默认赋值
			source: this.value,
			checkAll: true,
			isIndeterminate: false,
		}
	},
	created() {
		// this.allChange(true)
	},
	methods: {
		// 全选事件
		allChange(val) {
			let total = []
			for (const i of this.boxs) {
				total.push(i.value)
			}
			this.source = val ? total : []
			this.isIndeterminate = false
		},
		// 单选事件
		radioChange(val) {
			this.checkAll = val.length === this.boxs.length
			this.isIndeterminate = val.length > 0 && val.length < this.boxs.length
		},
	},
}
</script>

<style lang="scss" scoped>
.my-checkbox /deep/ .el-checkbox-group {
	min-height: 28px;
}
</style>